// $Id: PetriNetRelation.cs 124 2007-05-28 15:51:51Z xavex2k $

using System;
using System.Collections.Generic;
using Diagram.Model;

namespace PetriDiagram.Model
{
    [Serializable]
    public class PetriNetRelation : Relation
    {
        private int weight;
        private PetriNetModel net;

        public PetriNetRelation( PetriNetModel netModel )
            : base( netModel )
        {
            Weight = 1;
            net = netModel;
        }

        public int Weight
        {
            get { return weight; }
            set
            {
                weight = value;
                InvokeChanged();
            }
        }

        public override bool IsValidRelationBetween( Entity start, Entity end )
        {
            return base.IsValidRelationBetween( start, end ) &&
                   IsBetweenPlaceAndTransition( start, end ) &&
                   !ExistsConnection( start, end );
        }

        private bool ExistsConnection( Entity start, Entity end )
        {
            List<Relation> relations = new List<Relation>();

            foreach( Relation relation in net.Relations )
                if( relation.From == start && relation.To == end )
                    relations.Add( relation );

            if( relations.Count == 0 ||
                ( relations.Count == 1 && relations[ 0 ] == this ) )
                return false;
            else
                return true;
        }

        private static bool IsBetweenPlaceAndTransition( Entity start, Entity end )
        {
            return ( ( start is Place && end is Transition ) || ( start is Transition && end is Place ) );
        }

        //public override Entity Clone()
        //{
        //    return new PetriNetRelation( net );
        //}

        public override Diagram.IUndoable GetInstance()
        {
            return new PetriNetRelation( net );
        }
    }
}
